package com.yjd.back.resource;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.Model;
import com.yjd.comm.base.model.ResultModel;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.resource.service.IResourceService;
import com.yjd.comm.system.model.AdminModel;
import com.yjd.comm.system.service.IAdminService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.vo.Constant;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 以上、机构、项目发布时的各种图片上传
 * Created by yangchangyan on 2017/7/11.
 *
 * @param
 * @return
 * @throws
 */
@Controller("com.yjd.back.resource.ResourceController")
@Scope("prototype")
@RequestMapping("/resource")
public class ResourceController extends BaseControl {

    @Resource
    IResourceService resourceService;

    @Resource
    private IAdminService adminService;

    /**
     * 后台发布编辑内容时，图片预览空间加载预览图片
     *
     * @param type 1:机构，2、项目，3：医生，4：图片
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     */
    @RequestMapping(value = "/downloadAll")
    @ResponseBody
    public Map<String, Object> downloadAll(Integer type) throws Exception {
        List<Hashtable<String, Object>> fileList = new ArrayList<Hashtable<String, Object>>();

        // 取最近30分钟内上传的图片
        Long last10min = FrameUtil.getTime() - 12*60*60;
        List<ResourceModel> files = resourceService.getModelList(FrameUtil.newHashMap("create_time_lt", last10min, "ref_type", type), DbWREnums.READ);

        String path = null;
        for (ResourceModel file : files) {
            Hashtable<String, Object> hash = new Hashtable<String, Object>();
            hash.put("is_dir", false);
            hash.put("has_file", false);
            hash.put("filesize", 100);
            hash.put("is_photo", true);
            path = file.getPath();
            hash.put("filetype", path.substring(path.lastIndexOf(".") + 1));
            hash.put("filename", path);
            hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.getCreate_time()*1000)));
            fileList.add(hash);
        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("file_list", fileList);
        result.put("current_url", FrameUtil.getConstResource("public.remote.picture.url") + FrameUtil.getConstResource("FileDir"));
        return result;
    }

    /**
     * 上传图片
     *
     * @param multipartRequest
     * @param type 1:机构，2、项目，3：医生，4：图片
     * @return com.yjd.back.resource.ResourceController.UploadResponse
     * @throws
     */
    @RequestMapping(value = "/upload")
    public void upload(MultipartHttpServletRequest multipartRequest, Integer type) throws Exception {

        String uid = request.getParameter("uid");
        String sign = request.getParameter("sign");
        if (!this.uploadAuthor(uid, sign)) {
            return; // 验证不通过
        }

        ResourceModel res = new ResourceModel();
        res.setRef_type(ReferenceTypeEnum.parse(type).getCode());
        String remotefile = null;
        for(String key : multipartRequest.getFileMap().keySet()){
            remotefile = FileUtil.uploadFileToRemote(multipartRequest.getFileMap().get(key), ReferenceTypeEnum.parse(type), res);
        }

        ResultModel rm = new ResultModel(Constant.ResultEnum.SUCCESS, null, FrameUtil.getResource("文件上传成功！"), null);
        Map returnMap = new HashMap();
        returnMap.put("attachurl", ServletUtil.getFileUrl(remotefile));
        returnMap.put("name", remotefile);
        rm.setData(returnMap);

        ServletUtil.outputJsonMessage(response, rm.toMap());
    }

    public boolean uploadAuthor(String uid, String sign) throws NumberFormatException, Exception {
        boolean flag = false;
        Model m = this.adminService.getModelById(Long.parseLong(uid),DbWREnums.READ);
        String password = ((AdminModel) m).getPassword();
        flag = sign.equals(DigestUtils.md5Hex(password + uid));
        return flag;
    }
}